package com.work.shart.web.service.goods;

import com.work.shart.web.res.goods.GoodsRes;

import org.elasticsearch.index.query.DisMaxQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;

import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 全文检索服务类->文章
 */
@Service
public class GoodsEsService {

    @Autowired
    private IGoodsResService service;

    /**
     * 保存
     *
     * @param goodsRes
     * @return
     */
    public void save(List<GoodsRes> goodsRes) {
        service.saveAll(goodsRes);
    }

    /**
     * matchQuery       : 单个字段查询
     * matchAllQuery    : 匹配所有
     * multiMatchQuery  : 多个字段匹配某一个值
     * wildcardQuery    : 模糊查询
     * boost            : 设置权重,数值越大权重越大
     * 混合搜索
     *
     * @param content
     * @return
     */
    public List<GoodsRes> querySearch(String content) {
        DisMaxQueryBuilder disMaxQueryBuilder = QueryBuilders.disMaxQuery();
        QueryBuilder cate = QueryBuilders.matchQuery("classification.name", content);
        QueryBuilder title = QueryBuilders.wildcardQuery("hotTitle", content);
        QueryBuilder textArea = QueryBuilders.matchQuery("textArea", content);
        disMaxQueryBuilder.add(cate);
        disMaxQueryBuilder.add(title);
        disMaxQueryBuilder.add(textArea);
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
        builder.withQuery(disMaxQueryBuilder);
        NativeSearchQuery query = builder.build();
        return service.search(query).getContent();
    }


    /**
     * 文章热点
     *
     * @return
     */
    public Iterable<GoodsRes> all() {
        return service.findAll();
    }


}
